<template>
  <div class="alarm-view">
    <!-- 告警列表 -->
    <card ref="cardRef">
      <template #header>
        <div class="card-header" ref="headerRef">
          <span>告警列表</span>
          <div class="header-actions">
            <!-- 搜索和操作区域 -->
            <div class="search-area">
              <el-input v-model="searchForm.keyword" placeholder="请输入设备名称或告警信息" style="width: 200px;" clearable />
              <el-date-picker v-model="searchForm.dateRange" type="datetimerange" range-separator="至"
                start-placeholder="开始时间" end-placeholder="结束时间" style="width: 370px;" format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DDTHH:mm:ss.SSSZ" />
              <el-button type="primary" @click="handleSearch">
                <el-icon>
                  <Search />
                </el-icon>
                搜索
              </el-button>
              <el-button @click="handleReset">
                <el-icon>
                  <Refresh />
                </el-icon>
                重置
              </el-button>
              <el-button @click="refreshAlarms">
                <el-icon>
                  <Refresh />
                </el-icon>
                刷新
              </el-button>
              <el-button type="success" @click="handleExport">
                <el-icon>
                  <Download />
                </el-icon>
                导出
              </el-button>
            </div>
          </div>
        </div>
      </template>
      <ElementTable :data="alarmList" :tableTitle="tableColumns" :showPagination="true" :pageConfig="pageConfig" @selectChange="handleSelectChange">
        <template #alarmType="{ data }">
          <span :title="data.row.alarmType">{{ getAlarmTypeText(data.row.alarmType) }}</span>
        </template>
      </ElementTable>
    </card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed, onUnmounted, nextTick } from 'vue'
import { ElButton, ElIcon, ElInput, ElDatePicker } from 'element-plus'
import { Refresh, Search, Download } from '@element-plus/icons-vue'
import { info } from '@/utils/toast'
import { $getAlarmList, $exportAlarmList } from '@/api/alarm'
import type { Alarm, PageQuery } from '@/types'
import { getAlarmTypeText } from '@/types'
import { ExportUtil } from '@/utils/export'
import card from '@/components/card/index.vue'
import ElementTable from '@/components/ElementTable/index.vue'

// 告警数据
const alarmList = ref<Alarm[]>([])
const loading = ref(false)

// DOM引用
const cardRef = ref<HTMLElement>()
const headerRef = ref<HTMLElement>()

// 动态计算表格最大高度
const tableMaxHeight = computed(() => {
  // 使用视口高度减去固定区域高度
  // 整体高度 - header(60px) - 页面头部(120px) - 搜索区域(80px) - 分页区域(80px) - 内边距(60px)
  const viewportHeight = window.innerHeight
  const fixedHeight = 60 + 120 + 80 + 80 + 60 // 400px
  const availableHeight = viewportHeight - fixedHeight

  // 调试信息
  console.log('Viewport height:', viewportHeight)
  console.log('Fixed height:', fixedHeight)
  console.log('Available height:', availableHeight)

  // 最小高度200px，最大高度不超过800px
  return Math.max(200, Math.min(800, availableHeight))
})

// 监听窗口大小变化
const handleResize = () => {
  // 触发重新计算
  nextTick(() => {
    // 计算属性会自动重新计算
  })
}

// 搜索表单
const searchForm = ref({
  keyword: '',
  dateRange: null as [string, string] | null
})

// 分页配置
const pageConfig = ref({
  currentPage: 1,
  pageSize: 20,
  pageSizes: [10, 20, 50, 100],
  layout: 'total, sizes, prev, pager, next, jumper',
  total: 0,
  background: true,
  handleSizeChange: (size: number) => {
    pageConfig.value.pageSize = size
    pageConfig.value.currentPage = 1
    loadAlarmList()
  },
  handleCurrentChange: (page: number) => {
    pageConfig.value.currentPage = page
    loadAlarmList()
  }
})

// 表格列配置
const tableColumns = ref([
  { type: 'text', label: '告警ID', prop: 'id', width: '100' },
  { type: 'text', label: '设备名称', prop: 'deviceName' },
  {
    type: 'custom',
    label: '告警类型',
    prop: 'alarmType',
    name: 'alarmType'
  },
  { type: 'text', label: '告警信息', prop: 'alarmContent' },
  { type: 'time', label: '发生时间', prop: 'createTime', width: '180' },
])

// 加载告警列表
const loadAlarmList = async () => {
  try {
    loading.value = true
    const params: PageQuery = {
      page: pageConfig.value.currentPage,
      pageSize: pageConfig.value.pageSize,
      keyword: searchForm.value.keyword || undefined,
      start: searchForm.value.dateRange?.[0] || undefined,
      end: searchForm.value.dateRange?.[1] || undefined
    }

    // 确保时间格式正确
    if (params.start && params.end) {
      // 如果时间格式不是ISO格式，转换为ISO格式
      if (!params.start.includes('T')) {
        params.start = new Date(params.start).toISOString()
      }
      if (!params.end.includes('T')) {
        params.end = new Date(params.end).toISOString()
      }
    }

    const response = await $getAlarmList(params)
    alarmList.value = response.data.data || []
    pageConfig.value.total = response.data.total || 0
  } catch (error) {
    console.error('加载告警列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 方法

const refreshAlarms = () => {
  loadAlarmList()
}

const handleSearch = () => {
  pageConfig.value.currentPage = 1
  loadAlarmList()
}

const handleReset = () => {
  searchForm.value.keyword = ''
  // 重置时也设置默认时间范围为最近1小时
  setDefaultTimeRange()
  pageConfig.value.currentPage = 1
  loadAlarmList()
}

const handleExport = async () => {
  try {
    // 构建导出参数，使用当前的搜索条件
    const params: PageQuery = {
      page: 1, // 导出时通常从第一页开始
      pageSize: 10000, // 设置一个较大的值来获取所有数据
      keyword: searchForm.value.keyword || undefined,
      start: searchForm.value.dateRange?.[0] || undefined,
      end: searchForm.value.dateRange?.[1] || undefined
    }

    // 确保时间格式正确
    if (params.start && params.end) {
      if (!params.start.includes('T')) {
        params.start = new Date(params.start).toISOString()
      }
      if (!params.end.includes('T')) {
        params.end = new Date(params.end).toISOString()
      }
    }

    info('正在导出告警数据，请稍候...')
    
    // 调用导出接口
    const response = await $exportAlarmList(params)
    
    // 使用导出工具类处理响应数据
    const formatters = {
      alarmType: (value: any) => getAlarmTypeText(value),
      createTime: (value: any) => value ? new Date(value).toLocaleString() : ''
    }

    ExportUtil.handleApiResponse(response, {
      filename: ExportUtil.generateFilename('告警数据'),
      fileType: 'csv'
    }, formatters)
    
    info('告警数据导出成功！')
  } catch (error) {
    console.error('导出告警数据失败:', error)
    info('导出失败，请重试')
  }
}



const handleSelectChange = (selection: Alarm[]) => {
  console.log('选中的告警:', selection)
}

// 设置默认时间范围为最近1小时
const setDefaultTimeRange = () => {
  const now = new Date()
  const oneHourAgo = new Date(now.getTime() - 60 * 60 * 1000) // 1小时前
  
  // 格式化为日期选择器期望的格式 YYYY-MM-DDTHH:mm:ss.SSSZ
  const formatDate = (date: Date) => {
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    const hours = String(date.getHours()).padStart(2, '0')
    const minutes = String(date.getMinutes()).padStart(2, '0')
    const seconds = String(date.getSeconds()).padStart(2, '0')
    const milliseconds = String(date.getMilliseconds()).padStart(3, '0')
    
    return `${year}-${month}-${day}T${hours}:${minutes}:${seconds}.${milliseconds}Z`
  }
  
  const startTime = formatDate(oneHourAgo)
  const endTime = formatDate(now)
  
  searchForm.value.dateRange = [startTime, endTime]
}

// 生命周期
onMounted(() => {
  // 设置默认时间范围
  setDefaultTimeRange()
  // 加载告警列表
  loadAlarmList()
  // 添加窗口大小变化监听
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  // 移除窗口大小变化监听
  window.removeEventListener('resize', handleResize)
})
</script>

<style scoped>
.alarm-view {
  padding: 0;
  height: 100%;
  display: flex;
  flex-direction: column;
  min-height: 0;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 8px;
}

.search-area {
  display: flex;
  align-items: center;
  gap: 8px;
}
</style>